const SMSClient = require('@alicloud/sms-sdk');

class SmsSDK {
  constructor(config) {
    this.client = new SMSClient({
      accessKeyId: config.accessKeyId,
      secretAccessKey: config.secretAccessKey,
      endpoint: config.endpoint || 'https://dysmsapi.aliyuncs.com',
      regionId: config.regionId || 'cn-hangzhou'
    });
  }

  /**
   * 发送单条短信
   */
  async sendSms(params) {
    try {
      const response = await this.client.sendSMS({
        PhoneNumbers: Array.isArray(params.phoneNumbers) 
          ? params.phoneNumbers.join(',') 
          : params.phoneNumbers,
        SignName: params.signName,
        TemplateCode: params.templateCode,
        TemplateParam: params.templateParam 
          ? JSON.stringify(params.templateParam)
          : undefined
      });

      if (response.Code !== 'OK') {
        throw new Error(response.Message);
      }

      return response;
    } catch (error) {
      throw error;
    }
  }

  /**
   * 批量发送短信
   */
  async sendBatchSms(params) {
    try {
      const response = await this.client.sendBatchSMS({
        PhoneNumberJson: JSON.stringify(params.phoneNumbers),
        SignNameJson: JSON.stringify(params.signNames),
        TemplateCode: params.templateCode,
        TemplateParamJson: JSON.stringify(params.templateParams)
      });

      if (response.Code !== 'OK') {
        throw new Error(response.Message);
      }

      return response;
    } catch (error) {
      throw error;
    }
  }

  /**
   * 查询短信发送详情
   */
  async queryDetail(params) {
    try {
      const response = await this.client.queryDetail({
        PhoneNumber: params.phoneNumber,
        SendDate: params.sendDate,
        PageSize: params.pageSize?.toString() || '10',
        CurrentPage: params.currentPage?.toString() || '1'
      });

      if (response.Code !== 'OK') {
        throw new Error(response.Message);
      }

      return response;
    } catch (error) {
      throw error;
    }
  }
}

module.exports = SmsSDK; 